package ldh.im.handle;

import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import ldh.im.dto.business.TransferFile;
import ldh.im.dto.codec.CodecFactory;
import ldh.im.dto.codec.binery.TransferCode;
import ldh.im.dto.enmus.CodecType;

import java.io.File;
import java.io.RandomAccessFile;

@ChannelHandler.Sharable
public class FileSendHandler extends SimpleChannelInboundHandler<TransferFile> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TransferFile transferFile) throws Exception {
        File file = new File(transferFile.getPath());
        if (file.exists() && file.isFile()) {
            TransferCode transferCode = CodecFactory.getInstance().getTransfer(TransferFile.class, CodecType.binary);
            ByteBuf byteBuf = (ByteBuf) transferCode.getImCoder().encode(transferFile);
            ctx.write(byteBuf.readableBytes());
            ctx.writeAndFlush(byteBuf);
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
            FileRegion region = new DefaultFileRegion(randomAccessFile.getChannel(), 0, randomAccessFile.length());
            ctx.write(region);
            randomAccessFile.close();
        } else {
            throw new RuntimeException("文件不存在");
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}